package com.db.router.aop;

import com.db.router.context.ConnectionContext;
import com.db.router.dynamic.CustomConnection;
import com.db.router.context.TransactionContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author tianjiashu（mac）
 * @ClassName MultiDSTransactionJoinPoint.java
 * @Description 事务增强
 * @createTime 2023年07月12日 21:55:00
 */
@Aspect
@Component
public class MultiDSTransactionJoinPoint {

    private final Logger logger = LoggerFactory.getLogger(MultiDSTransactionJoinPoint.class);

    @Pointcut("@annotation(com.db.router.annotation.MultiDSTransaction)")
    public void transactPoint() {}

    @Around("transactPoint()")
    public Object multiTranAop(ProceedingJoinPoint joinPoint) throws Throwable {
        // 开启事务
        TransactionContext.openTran();
        try {
            // 执行业务
            Object proceed = joinPoint.proceed();
            // 提交事务
            for (CustomConnection connection : ConnectionContext.getConnections()) {
                connection.commitMultiDbTran();
                connection.closeMultiDbTran();
            }
            logger.info("SQL 执行完毕！事务已提交");
            return proceed;
        } catch (Throwable t) {
            for (CustomConnection connection : ConnectionContext.getConnections()) {
                // 事务回滚
                connection.rollback();
                connection.closeMultiDbTran();
            }
            logger.error("执行失败！事务已回滚");
            throw t;
        } finally {
            // 清空 事务 连接，关闭当前事务
            ConnectionContext.clear();
            TransactionContext.closeTran();
        }
    }
}

